package cn.chinaflame.pagodas.pool.forkjoin;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;

import cn.chinaflame.pagodas.service.WrmNIService;
import cn.chinaflame.pagodas.spring.ApplicationContextHolder;
import cn.chinaflame.pagodas.utils.LightAlgo.LightOp;
import cn.chinaflame.pagodas.vo.LightVO;

public class LightTask1 extends RecursiveTask<List<LightVO>> {

 
//	private static final int THRESHOLD = 2;
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1690655507552167040L;

	private static final Logger logger = LoggerFactory.getLogger(LightTask1.class);

	@Autowired
	private WrmNIService wrmNIService;
	
//	@Autowired
//	private PaLightsLogService paLightsLogService;//点灯、清灯日志Service
	
	private ArrayList<String> lightnos;//灯位编号
	private LightOp op;//操作类型，寻灯，安灯，清灯，检查灯位中的一种
	private JSONArray lightvos;//安灯参数jsonarray
    private Integer start;
    private Integer end;
    private static final int THRESHOLD =16;
    private static final int processors = Runtime.getRuntime().availableProcessors()-1;//阀门值
    
    public LightTask1() {super();}
    public LightTask1(Integer start, Integer end) {
		super();
	    this.start = start;
        this.end = end;
	}
	public LightTask1(Integer start, Integer end,JSONArray lightvos,LightOp op) {
		super();
		this.lightvos = lightvos;
		this.op = op;
	    this.start = start;
        this.end = end;
	}
	public LightTask1(Integer start, Integer end,ArrayList<String> lightnos,LightOp op) {
		super();
		this.lightnos = lightnos;
		this.op = op;
	    this.start = start;
        this.end = end;
	}
	public ArrayList<String> getLightnos() {
		return lightnos;
	}
	public void setLightnos(ArrayList<String> lightnos) {
		this.lightnos = lightnos;
	}
	public LightOp getOp() {
		return op;
	}
	public void setOp(LightOp op) {
		this.op = op;
	}


    //实现compute 方法来实现任务切分和计算
    @Override
    protected List<LightVO> compute() {
    	List<LightVO> list = Lists.newArrayList();
    	LightWorkerThread thread = (LightWorkerThread)Thread.currentThread();
    	thread.addTask();
        boolean canCompute = (end - start) <= THRESHOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++)
				try {
					call();
				} catch (Exception e) {
					logger.info(e.getMessage());
				}
        } else {
            //如果任务大于阀值，就分裂成两个子任务计算
            int mid = (start + end) / 2;
            LightTask1 leftTask = new LightTask1(start, mid);
            LightTask1 rightTask = new LightTask1(mid + 1, end);
            
            //执行子任务
            leftTask.fork();
            rightTask.fork();
            invokeAll(leftTask, rightTask);
            //等待子任务执行完，并得到结果
            List<LightVO> leftResult = leftTask.join();
            List<LightVO> rightResult = rightTask.join();
            list.addAll(leftResult);
            list.addAll(rightResult);
//            sum = leftResult + rightResult;
        }
        return list;
    }
	
	private List<LightVO> call() throws Exception {
		List<LightVO> vos = Lists.newArrayList();
		if(wrmNIService == null)
			 wrmNIService = ApplicationContextHolder.getBean(WrmNIService.class);//若调用WebService的service为空。则生成一个并打开开关
		wrmNIService.lighton();
		String lights;
		switch(op) {
		case lightCheck://执行检查灯位线程并打印信息
			lights = String.join(",", lightnos);
			vos = wrmNIService.lightCheck(lights);
			logger.info(" running on 线程名：" + Thread.currentThread().getName() + "优先级" + Thread.currentThread().getPriority());
			break;
		case lightSend://执行安灯线程并打印信息
			lights = JSONArray.toJSONString(lightvos);
			vos = wrmNIService.lightSend(lights);
			logger.info(" running on 线程名：" + Thread.currentThread().getName() + "优先级" + Thread.currentThread().getPriority());
			break;
		case lightClear://执行清灯线程并打印信息
			lights = String.join(",", lightnos);
			vos = wrmNIService.lightClear(String.join(",", lightnos));
			logger.info(" running on 线程名：" + Thread.currentThread().getName() + "优先级" + Thread.currentThread().getPriority());
			break;
		case lightSearch:////执行寻灯线程并打印信息
			lights = String.join(",", lightnos);
			vos = wrmNIService.lightSearch(String.join(",", lightnos));
			logger.info(" running on 线程名：" + Thread.currentThread().getName() + "优先级" + Thread.currentThread().getPriority());
			break;
			default://否则属于无效操作命令
			logger.info(" running on 操作类型不合法，无效线程：" + Thread.currentThread().getName());
			break;
		}
//		logger.info(JSONArray.toJSONString(vos));
		return vos;
	}
	
	public JSONArray getLightvos() {
		return lightvos;
	}
	public void setLightvos(JSONArray lightvos) {
		this.lightvos = lightvos;
	}
	 
}
